package cxm.mmp.aud;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import cxm.lib.util.MyLog;

public class FileRecordingSave implements IRecordingSource {
	File file = null;
	DataOutputStream dos = null;

	public FileRecordingSave(File file) {
		this.file = file;
	}

	public int onRecordStart() {
		try {
			this.dos = new DataOutputStream(new BufferedOutputStream(
					new FileOutputStream(this.file)));
			return 0;
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot open file to write: " + e);
			return -1;
		}
	}
	
	public int onRecordData(byte []data, int start, int num) {
		int i = 0;
		for (i = 0; i < num; i++) {
			try {
				this.dos.writeByte(data[start + i]);
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot write data at " + (start + i));
			}
		}

		return i;
	}
	
	public int onRecordStop() {
		try {
			this.dos.close();
			return 0;
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot close record file: " + e);
			return -1;
		}
	}
	
	public int onRecordError(IRecordingSource.RecordError error, int errno) {
		MyLog.Log(MyLog.Level.Debug, "On Recording error");
		return 0;
	}
}
